import {
	StorageHelper
} from './storage.js'

const userStorage = new StorageHelper('user')

const API_URL = 'http://cool.ldqc.xyz:7777'

// {String }url:请求的接口地址 
// {String} method:请求方式 GET,POST.... 
// {Object} data:要传递的参数 
//二次封装wx.request
export const request = (url, method, data, contentType = ContentTypeEnum.FORM_URLENCODED) => {
	return new Promise((resolve, reject) => {
		let _url = `${API_URL}${url}`;
		let requestData = data;
		let requestHeader = {
			'content-type': contentType
		};
		let token = userStorage.get('token');
		if (token) {
			requestHeader['token'] = token
		}
		if (method === RequestEnum.GET) {
			let params = [];
			for (let key in data) {
				params.push(`${key}=${data[key]}`);
			}
			if (params.length > 0) {
				_url += `?${params.join('&')}`;
			}
			requestData = null;
		}
		wx.request({
			url: _url,
			data: requestData,
			method,
			header: requestHeader,
			success: res => {
				resolve(res.data)
			},
			fail: err => {
				reject(err)
			}
		})
	})
};

/**
 * 单文件文件上传
 * @return Promise {
 *	 resolve: 图片路径
 *   reject: 失败信息
 * }
 */
export const upload = filePath => {
	return new Promise((resolve, reject) => {
		wx.uploadFile({
			url: `${API_URL}/file/upload`,
			filePath,
			name: 'file',
			header: {
				'content-type': ContentTypeEnum.MULTIPART_FORMDATA
			},
			success: res => {
				resolve(JSON.parse(res.data).body)
			},
			fail: err => {
				reject(err)
			}
		})
	})
}

export const RequestEnum = {
	GET: 'get',
	POST: 'post',
	PUT: 'put',
	DELETE: 'delete'
}

export const ContentTypeEnum = {
	FORM_URLENCODED: 'application/x-www-form-urlencoded',
	JSON: 'application/json',
	XML: 'application/xml',
	TEXT: 'text/plain',
	HTML: 'text/html',
	MULTIPART_FORMDATA: 'multipart/form-data'
};